<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use DB;
use Gregwar\Captcha\CaptchaBuilder;

class loginController extends Controller
{
    //
    public function index(Request $request)
    {
    	$input = $request->all();
        // dd(session('mycode'));
        // dd($input);
        if($input['yzm'] == session('mycode')){
            $list = DB::table('manager')->select('uname', 'passwd', 'id')->get();
            // 循环判断用户名和密码是否输入正确
            for($j = 0; $j <= count($list)-1; $j++){
                if(($list[$j]->uname == $request->input('uname')) && ($list[$j]->passwd == md5($request->input('passwd')))){
                    // 将用户名存入session
                    session(['username' => $request->input('uname')]);
                    // 将用户id存入session
                    session(['id' => $list[$j]->id]);
                    return redirect('/admin/main');
                }
            }
            return redirect('login')->with('msg', '用户名或密码错误！');
        }
        return redirect('login')->with('msg', '验证码输入错误！');
    }

    // 注册管理员
    public function register(Request $request)
    {
        if($request->input('passwd') == $request->input('repasswd')){
            $input = $request->only('uname', 'email', 'useradmin', 'description');
            $res = DB::table('manager')->insertGetId($input);
            // 用MD5对密码加密
            DB::table('manager')->where('id', $res)->update(['passwd' => md5($request->input('passwd'))]);
            if($res > 0){
                return redirect('login')->with('msg', '恭喜您,注册成功！');
            }
        }else{
            return redirect('login')->with('msg', '两次密码不一致，请重新注册！');
        }
    }

    // 退出登录,删除session(username)
    public function outlogin(Request $request)
    {
        $request->session()->forget('username');
        return redirect('login');
    }

    // 验证码
    public function yzm($tmp)
    {
        // $builder = new CaptchaBuilder;
        // $builder->build();
        // header('content-type:image/jpeg');
        // $builder->output();

        //生成验证码图片的builder对象，
        $builder = new CaptchaBuilder;
        // 设置验证码的宽高字体
        $builder->build(150,50,null);
        //获取验证码中的内容
        $data = $builder->getPhrase();
        //把验证码的内容闪存到session里面
        session()->flash('mycode',$data);

        //告诉浏览器，这是一张图片
        // header('content-type:image/jpeg');
        //生成图片
        // $builder->output();die;

        return response($builder->output())->header('Content-type','image/jpeg');
    }
}